package io.gitee.thghh.generate.core.datatype;

import com.github.drinkjava2.jdialects.Dialect;
import com.github.drinkjava2.jdialects.Type;
import com.github.drinkjava2.jdialects.constants.StringPool;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import io.gitee.thghh.generate.core.entity.TypeConfig;
import io.gitee.thghh.generate.core.service.TypeConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 键入配置初始化数据
 *
 * @author pengzhikang
 * @date 2025/03/30
 * @since 1.0.0
 */
@Slf4j
@Component
@Transactional(rollbackFor = Exception.class)
public class TypeConfigInitData {

    @Autowired
    private TypeConfigService typeConfigService;

    @PostConstruct
    public void initData() {
        List<Dialect> dialectList = Arrays.asList(Dialect.MySQLDialect, Dialect.OracleDialect, Dialect.PostgreSQLDialect, Dialect.H2Dialect);
        for (Dialect dialect : dialectList) {
            dialectInitData(dialect);
        }
    }

    /**
     * 方言初始化数据
     *
     * @param dialect 方言
     * @author pengzhikang
     * @date 2025/03/30
     */
    public void dialectInitData(Dialect dialect) {
        String dialectName = dialect.getName().replace("Dialect", StringPool.EMPTY);

        // 数据是否存在
        QueryChain<TypeConfig> queryChain = typeConfigService.queryChain().eq(TypeConfig::getDialect, dialectName);
        TypeConfig hasData = typeConfigService.getOne(queryChain);
        if (hasData != null) {
            return;
        }

        List<TypeConfig> typeConfigList = new ArrayList<>();
        TypeConfig typeConfig = null;
        log.info("{} type config init data", dialectName);
        Map<Type, String> typeMappings = dialect.typeMappings;
        for (Map.Entry<Type, String> entry : typeMappings.entrySet()) {
            String className = TypeMapUtil.dialectTypeToClassName(entry.getKey());

            typeConfig = new TypeConfig();
            typeConfig.setDialect(dialectName);
            typeConfig.setDbType(entry.getKey().name());
            typeConfig.setBaseType(className);
            typeConfig.setBoxType(className);

            typeConfigList.add(typeConfig);
        }

        typeConfigService.saveBatch(typeConfigList);
    }
}
